package com.dongxing.concyrrency.chapter9;

import java.util.stream.Stream;

/**
 * 多生产者，多消费者
 *
 * @author XavierDong
 **/
public class ProduceConsumerVersion3 {

    private int i = 0;

    private final Object LOCK = new Object();

    private volatile Boolean isProduced = Boolean.FALSE;

    private void produce() {

        synchronized (LOCK) {
            while (isProduced) {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            i++;
            System.out.println("P->" + i);
            // 唤醒消费者去消费
            LOCK.notifyAll();
            isProduced = Boolean.TRUE;
        }
    }


    private void consume() {
        synchronized (LOCK) {
            while (!isProduced) {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("c->" + i);
            // 消费完了，唤醒生产者去生产
            LOCK.notifyAll();
            isProduced = Boolean.FALSE;

        }
    }

    public static void main(String[] args) {

        ProduceConsumerVersion3 pc = new ProduceConsumerVersion3();

        Stream.of("P1", "P2").forEach(n ->
                new Thread(n) {
                    @Override
                    public void run() {
                        while (true) {
                            pc.produce();
                        }
                    }
                }.start());

        Stream.of("C1", "C2").forEach(n ->
                new Thread(n) {
                    @Override
                    public void run() {
                        while (true) {
                            pc.consume();
                        }
                    }
                }.start());

    }
}
